package com.hsd.controller;

import com.hsd.model.RUser;
import com.hsd.service.RUserService;
import com.hsd.util.AjaxJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/account")
public class AccountController {
     
    @Autowired
    private RUserService userService;
    
    @RequestMapping(value="/password")
    public ModelAndView password(HttpSession session){      
        ModelAndView mav = new ModelAndView("password");
        return mav;    
    }
    
    @RequestMapping(value="/information")
    public ModelAndView information(HttpSession session){      
        ModelAndView mav = new ModelAndView("information");
        RUser user = (RUser) session.getAttribute("user");
        mav.addObject(user);
        return mav;    
    }
    

    @RequestMapping(value ="checkPassword", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson checkPassword(HttpSession session, @RequestParam(value="oldPassword")String oldPassword){
        
        AjaxJson j = new AjaxJson();
        RUser user = (RUser)session.getAttribute("user");
        int userId = user.getUserId();
        String password = userService.selectPasswordById(userId);
        if (!password.equals(oldPassword)) {
            j.setSuccess(true);
        } else {
            j.setSuccess(false);
        }
        return j;
        
    }
    
    @RequestMapping(value ="editPassword", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson editPassword(HttpSession session, @RequestParam(value="newPassword")String newPassword){
        
        AjaxJson j = new AjaxJson();
        RUser user = (RUser)session.getAttribute("user");
        Integer userId = user.getUserId();
        userService.updatePasswordById(userId.toString(), newPassword);
        j.setSuccess(true);
        return j;        
    }
    
    @RequestMapping(value ="editInformation", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson editInformation(HttpSession session, @RequestParam(value="phone")String phone,
                                    @RequestParam(value="email")String email,
                                    @RequestParam(value="address")String address){
        
        AjaxJson j = new AjaxJson();
        //String userId = (String) session.getAttribute("userId");
        RUser user = (RUser) session.getAttribute("user");
        user.setPhone(phone);
        user.setEmail(email);
        user.setAddress(address);
        userService.updateUserById(user);
        j.setSuccess(true);
        return j;
        
    }
}

